import threading
from libs.svr.settings import settings


class TComponentManager:
    def __init__(self):
        self.rootPath = ""
        self.compTypes ={}
        self.components ={}
        #公共函数
        self.commonActions ={}
        self.tag = {}
    def log(self , component ,  data):
        print(component , data)
    def registCompType(self , typeName , compType):
        self.compTypes[typeName] = compType
    def registCommonAction(self , cateCode , actionCode  , actionHandler , tags):
        res ={}
        try:
            if not  cateCode in self.commonActions.keys():
                self.commonActions[cateCode] = {}
            cate = self.commonActions[cateCode]
            cate[actionCode]={
                "cateCode": cateCode ,
                "actionCode": actionCode ,
                "tags" : tags,
                "handle" : actionHandler
            }
            res ={
                "cateCode": cateCode ,
                "actionCode": actionCode ,
                "tags" : tags,
            }
        except Exception as er:
            self.log(self , er)
        return  res
    def getCommonAction(self , cateCode , actionCode ):
        res ={}
        try:
            pass
        except Exception as er:
            self.log(self , er)
        return  res
    def loadComps(self ):
        try:
            settings.loadByFn(settings.settingsFn)
            for compTypeCode in settings.info['components']:
                if compTypeCode in self.compTypes.keys():
                    compType = self.compTypes[compTypeCode]
                    for compCode in settings.info['components'][compTypeCode].keys():
                        try:
                            comp = compType(self)
                            comp.typeCode = compTypeCode
                            comp.compCode = compCode
                            compKey = f"{compTypeCode}/{compCode}"
                            self.components[compKey] = comp
                            comp.handlers['startService'] = comp.startService
                            comp.handlers['stopService'] = comp.stopService
                            comp.handlers['restartService'] = comp.restartService
                            comp.handlers['reloadSettings'] = comp.reloadSettings
                            comp.startService()
                            print(self , comp.compCode , comp.compSettings)
                        except Exception as erComp:
                            self.log(self , erComp)
        except Exception as er:
            self.log(self , er)
    def getComp(self , compTypeCode , compCode):
        res:TComponent = None
        try:
            if ( compTypeCode in self.compTypes.keys()):
                compKey = f"{compTypeCode}/{compCode}"
                if compKey in self.components.keys():
                    res = self.components[compKey]
        except Exception as er:
            self.log(self , er)
        return res
class TComponent:
    def __init__(self , _maneger:TComponentManager):
        self.manager = _maneger
        self.typeCode = ""
        self.compCode = ""
        self.handlers ={}
        self.serviceThread:threading.Thread = None
        self.running = False
        self._settings = None
    @property
    def compSettings(self):
        res={}
        try:
            if self._settings==None:
                if self.typeCode in settings.info["components"].keys():
                    if self.compCode in settings.info["components"][self.typeCode].keys():
                        cs = settings.info["components"][self.typeCode][self.compCode]
                        res.update(cs)
                        self._settings = res
            else:
                res = self._settings
        except Exception as er:
            self.manager.log(self, er)
        return res
    def beforeStartService(self):
        pass
    def serviceHandler(self):
        try:
            pass
        except Exception as erBrfore:
            self.manager.log(self, erBrfore)
    def startService(self):
        try:
            if not self.running:
                try:
                    self.beforeStartService()
                except Exception as erBrfore:
                    self.manager.log(self, erBrfore)
                self.serviceThread = threading.Thread(target=self.serviceHandler , daemon=True)
                self.running = True
                self.serviceThread.start()

        except Exception as er:
            self.manager.log(self, er)
    def stopService(self):
        try:
            self.running = False
        except Exception as er:
            self.manager.log(self, er)
    def restartService(self):
        try:
            self.stopService()
            self.startService()
        except Exception as er:
            self.manager.log(self, er)
    def reloadSettings(self):
        res={
            "status":0
        }
        try:
            settings.loadByFn(settings.settingsFn)
            res['status']=1
            self._settings = None
        except Exception as er:
            self.manager.log(self, er)
        return res

manager = TComponentManager()
